// MSVC
#include<Windows.h>
#include<iostream>
#include<TlHelp32.h>
#include<vector>
#include<algorithm>
#include <tlhelp32.h>

using namespace std;

//定义结构：进程PID、进程名称
struct ProcessInfo
{
	DWORD PID;
	string PName;
	ProcessInfo(DWORD PID, string PNmae) : PID(PID), PName(PNmae) {}

	//排序条件：PID 从小到大降序
	bool operator < (const ProcessInfo& rhs) const {
		return (PID < rhs.PID);
	}
}


// WCHAR 转换为 std::string
string WCHAR2String(LPCWSTR pwszSrc)
{
	int nLen = WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, NULL, 0, NULL, NULL);
	if (nLen <= 0)
		return std::string("");

	char* pszDst = new char[nLen];
	if (NULL == pszDst)
		return string("");

	WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, pszDst, nLen, NULL, NULL);
	pszDst[nLen - 1] = 0;

	std::string strTmp(pszDst);
	delete[] pszDst;

	return strTmp;
}

//获取当前系统的所有进程PID
vector<ProcessInfo> GetProcessInfo()
{
	STARTUPINFO st;
	PROCESS_INFORMATION pi;
	PROCESSENTRY32 ps;
	HANDLE hSnapshot;
	vector<ProcessInfo> PInfo;

	ZeroMemory(&st, sizeof(STARTUPINFO));
	ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
	st.cb = sizeof(STARTUPINFO);
	ZeroMemory(&ps, sizeof(PROCESSENTRY32));
	ps.dwSize = sizeof(PROCESSENTRY32);

	//拍摄进程快照
	hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

	if (hSnapshot == INVALID_HANDLE_VALUE)
	{
		//快照拍摄失败
		return PInfo;
	}

	if (!Process32First(hSnapshot, &ps))
	{
		return PInfo;
	}

	//将进程PID、进程名称存到容器Vector中
	do
	{
		PInfo.emplace_back(ps.th32ProcessID, WCHAR2String(ps.szExeFile));

	} while (Process32Next(hSnapshot, &ps));

	//关闭快照句柄
	CloseHandle(hSnapshot);

	//排序
	sort(PInfo.begin(), PInfo.end());

	return PInfo;
}

static void getMemoryVal(int64_t &pid, int64_t &addr) {
	// 打开进程
	HANDLE hProcess;
	hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);

	// 读取内存中的值
	int value;
	bool r = ReadProcessMemory(hProcess, (LPCVOID)addr, &value, sizeof(value), NULL);

	//cout << r << endl;
	// 关闭进程句柄
	CloseHandle(hProcess);

	// 打印读取到的值
	//cout << addr << " = " << value << endl;

	HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
	SetConsoleTextAttribute(handle, FOREGROUND_INTENSITY | 3);
	printf("0x%016lx = %d", (int)addr, value);
	SetConsoleTextAttribute(handle, FOREGROUND_INTENSITY | 7);
}

static int setMemoryVal(int64_t &process_id, int64_t &memory_addr) {
	string input;

	cout << "temp = ";
	cin >> input;

	int newVal = atoi(input.c_str());

	// 定义要修改的PID和地址
	DWORD pid = process_id;
	LPVOID address = (LPVOID)memory_addr;

	// 获取目标进程句柄
	HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
	if (hProcess == NULL) {
		cout << "进程打开失败: " << GetLastError() << endl;
		return 1;
	}

	// 写入新值
	BOOL writeResult = WriteProcessMemory(hProcess, address, &newVal, sizeof(newVal), NULL);
	if (writeResult == FALSE) {
		cout << "内存修改失败: " << GetLastError() << endl;
		CloseHandle(hProcess);
		return 1;
	}

	cout << "成功修改内存" << endl;

	CloseHandle(hProcess);

	getMemoryVal(process_id, memory_addr);
	return 0;
}

int main(int argc, char* argv[])
{
	vector<ProcessInfo> PInfo = GetProcessInfo();

	if (PInfo.size())
	{
		cout << "编号\t进程对应id(十进制)" << endl;
		for (vector<DWORD>::size_type iter = 0; iter < PInfo.size(); iter++)
		{
			cout << iter << "\t\t" << dec << PInfo[iter].PID << "\t" << PInfo[iter].PName.c_str() << endl;
		}
	}
	else
	{
		cout << "未找到进程" << endl;
	}

	int64_t pid, addr;


	cout << endl << "--------------------------------------" << endl << endl;

	cout << "进程ID" << endl << "> ";
	cin >> pid;
	cout << endl;

	cout << "内存地址" << endl << "> ";
	cin >> hex >> addr;
	cout << endl;

	int flag = 0;

	while (1) {
		cout << endl << "-----------------------" << endl
			 << "1. 读取" << endl
			 << "2. 修改" << endl
			 << "0. 退出" << endl
			 << "-----------------------" << endl << "> ";

		cin >> flag;

		switch (flag)
		{
		case 1:
			getMemoryVal(pid, addr);
			break;
		case 2:
			setMemoryVal(pid, addr);
			break;
		default:
			return 0;
		}
	}

	cout << "程序退出" << endl;
	system("pause");

	return 0;
}